import subprocess
import time
import re
def ipcheck(ip,filename):
    """
    检查某个网段里ip的使用情况
    """
    with open('check_result.txt','a+') as fp:
        subprocess.run('ping -c 4 '+ip+' > '+filename,shell=True)
        time.sleep(2)
        with open(filename,'r') as fp2:
            fp2.seek(0)
            if re.search(r'100% packet loss',fp2.read())==None:
                fp.write(ip+'已被使用\n')
            else:
                fp.write(ip+'未被使用\n')

import threading

def main():
    network=input('输入需要检测的网段:')
    lst = network.split('.')
    network = lst[0] + '.' + lst[1] + '.' + lst[2] + '.'
    t_list=[]
    global count
    for i in range(1,256):
        filename = 'ping' + str(i) + '.txt'
        t=threading.Thread(target=ipcheck,args=(network+str(i),filename))
        t.start()
        t_list.append(t)
    for t in t_list:
        t.join()
    subprocess.run('rm -rf ping*',shell=True)
main()
